package com.sx.shop.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sx.shop.entity.Category;
import com.sx.shop.entity.Product;
import com.sx.shop.entity.User;
import com.sx.shop.mapper.CategoryMapper;
import com.sx.shop.mapper.ProductMapper;
import com.sx.shop.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductService
{
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    public String addProduct(Product product)
    {
        if(product!=null)
        {
            if(productMapper.addProduct(product)==1)
                return "添加成功";
        }
        return "添加失败";
    }
    public String delete(Integer proId)
    {
        if(proId!=null)
        {
            if(productMapper.deleteByPid(proId)==1)
            {
                return "删除成功";
            }
        }
        return "操作失败";
    }

    public String updateInfo(Product product)
    {
        if(product!=null)
        {
            if(productMapper.updateInfo(product)==1)
                return "更新成功";
        }
        return "修改失败";
    }
    public String updateBind(Integer id, String ids)
    {
        String[] array = ids.split(",");
        Product product=new Product();
        product.setCategory_id(Integer.parseInt(array[0]));
        product.setId(id);
        if(productMapper.updateInfo(product)==1)
            return "操作成功";
        else return "操作失败";
    }

    public ResultVo getAll(String keyword , Integer page , Integer limit)
    {
        ResultVo vo = new ResultVo();
        PageHelper.startPage( page , limit);//代码下的第一个查询，有分页效果
        List<Product> list = productMapper.getAll(keyword);
        for (Product p:list)
        {
            Category category=categoryMapper.selectById(p.getCategory_id());
            p.setCategoryName(category.getName());
        }
        PageInfo<Product> pageInfo = new PageInfo<>(list);
        vo.setData(pageInfo.getList());
        vo.setCount(pageInfo.getTotal());
        return vo;
    }

    public Product findById(Integer id)
    {
        return productMapper.findById(id);
    }

    public List<Product> findAll()
    {
        return productMapper.findAll();
    }

}
